from flask import Flask, request, jsonify
import requests
from config.configBusiness import ai_make_config  # 导入 AiMake 类的实例对象
from https.httputils import DataManager
from video_gen import create_video, video_template, extract_path
from werkzeug.utils import secure_filename
from flask_cors import CORS
from datetime import datetime
import os
from https.UploadPaths import UploadPaths
from job.job import job
from apscheduler.schedulers.background import BackgroundScheduler
from config.template import request_body_dict
import random

app = Flask(__name__)
CORS(app)


@app.route('/')
def index():
    return 'Hello,this is your Python web app!'


# 查询Gif列表数据
@app.route('/ai/gif/list', methods=['GET'])
def gifList():
    data_manager = DataManager(api_url=ai_make_config.urlGif)
    response_data = data_manager.get_data(
        request.args.get('page_no'), request.args.get('page_size'))
    if response_data and response_data.code == 1:
        data_to_return = {
            'count': response_data.data.get('count'),
            'list': response_data.data.get('list') if 'list' in response_data.data else []
        }
        return jsonify(data_to_return)

    return jsonify({'error': 'Failed to fetch data'})


# 查询PNG列表数据
@app.route('/ai/png/list')
def pngList():
    data_manager = DataManager(api_url=ai_make_config.urlPng)
    response_data = data_manager.get_data(
        request.args.get('page_no'), request.args.get('page_size'))
    if response_data and response_data.code == 1:
        data_to_return = {
            'count': response_data.data.get('count'),
            'list': response_data.data.get('list') if 'list' in response_data.data else []
        }
        return jsonify(data_to_return)

    return jsonify({'error': 'Failed to fetch data'})


# AI>>chatGPT 文案
@app.route('/ai/text/genDetail')
def genDetail():
    text = request.args.get('text')
    data_manager = DataManager(api_url=ai_make_config.urlOpen)
    response_data = data_manager.post_data_gpt(request_body_dict(text))
    return response_data


# 上传图片单个
@app.route('/ai/file/upload', methods=['POST'])
def upload_file():
    try:
        uploaded_file = request.files['file']
        file_type = request.form['fileType'].lower()  # 获取 fileType 参数并转换为小写
        # 判断文件类型是否在映射关系中
        upload_paths = UploadPaths()
        upload_folder = upload_paths.get_path(file_type)
        if uploaded_file:
            filename = secure_filename(uploaded_file.filename)
            current_time = datetime.now().strftime("%Y%m%d%H%M%S")
            file_name, file_extension = os.path.splitext(filename)
            new_filename = f"{file_name}_{current_time}{file_extension}"
            file_path = os.path.join(upload_folder, new_filename)
            uploaded_file.save(file_path)

            # 构建返回的 AjaxResult 类似的数据
            ajax = {
                "code": 0,
                "url": file_path,
                "fileName": filename,
                "newFileName": new_filename,
                "originalFilename": filename,
            }

            return jsonify(ajax)
        else:
            return jsonify({"code": -1, "message": "File not found"})
    except Exception as e:
        return jsonify({"code": -1, "message": str(e)})  # 出错时返回错误信息


# 上传图片
@app.route('/ai/make/uploadFiles', methods=['POST'])
def uploadFiles():
    data = request.json
    file_type = data.get('fileType')
    urls = [item['url'] for item in data.get('myFileList')]
    upload_paths = UploadPaths()
    upload_folder = upload_paths.get_path(file_type)
    downloaded_files = []
    for url in urls:
        response = requests.get(url)
        if response.status_code == 200:
            filename = os.path.basename(url)
            current_time = datetime.now().strftime("%Y%m%d%H%M%S")
            file_path = os.path.join(
                upload_folder, current_time + "_" + filename)
            with open(file_path, 'wb') as f:
                f.write(response.content)
            downloaded_files.append(file_path)

    return jsonify({"code": 0, "message": "Files downloaded successfully", "file_paths": downloaded_files})


# 视频合成
@app.route('/ai/make/makeVideo', methods=['POST'])
def makeVideo():
    data = request.json  # 获取传入的 JSON 数据
    # 处理 data 中的数据，例如：
    param = data.get('contentParam')

    text_params = param.get('textFields')
    gifs_params = param.get('gifs')
    png_param = extract_path(param.get('pngUrl'))
    music_param = extract_path(data.get('musicFile').get("url"))
    for i in range(0, 360, 36):
        # 在这里执行每次迭代时的操作
        gifs_params[0]["angleGif"] = i
        create_video(text_params, gifs_params, png_param, music_param)
    return None


# 视频自动合成
@app.route('/video_compositing', methods=['GET'])
def video_compositing():
    # 无文案模板
    # 51 ，47
    # 有文案模板
    # 4 ，54 ， 16 ，
    video_template(48)
    return ">>>Video compositing successful!"


def initialize_scheduler():
    scheduler = BackgroundScheduler()
    scheduler.add_job(job, 'interval', minutes=1)  # 每隔3分钟执行一次任务
    scheduler.start()


@app.route('/video/get_path/<string:template_id>', methods=['GET'])
def video_get_path(template_id):
    # 无文案模板
    # 51 ，47
    # 有文案模板
    # 4 ，54 ， 16 ，
    # template = [51, 47, 4, 54, 16]
    # probabilities = [0.5, 0.2, 0.2, 0.2, 0.2]
    # selected = random.choices(template, weights=probabilities)[0]
    # 判断template_id是否包含下划线
    # 下级
    lower = None
    if '_' in template_id:
        # 使用split方法拆分字符串
        template_id, lower = map(int, template_id.split('_'))
    return video_template(template_id, lower)


# TODO 在程序启动时执行初始化
# initialize_scheduler()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port='5000', threaded=True)
